<template>


  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px" label-width="68px">
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="queryParams.nickname" class="!w-240px" clearable placeholder="请输入用户昵称"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="queryParams.mobile" class="!w-240px" clearable placeholder="请输入手机号"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="注册时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-240px" end-placeholder="结束日期"
          start-placeholder="开始日期" type="daterange" value-format="YYYY-MM-DD HH:mm:ss" />
      </el-form-item>

      <el-form-item label="所属公司" prop="status" v-if="orgFilterVisible">
        <el-select v-model="queryParams.orgId" placeholder="请选择所属公司" clearable class="!w-240px">
          <el-option v-for="org in orgOptions" :key="org.orgId" :label="org.orgName" :value="org.orgId" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button @click="setOrg" v-if="orgFilterVisible">
          <Icon class="mr-5px" icon="ep:bell-filled" />
          划拨
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :show-overflow-tooltip="true" :stripe="true"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" />
      <el-table-column align="center" label="用户编号" prop="id" />
      <el-table-column align="center" label="头像" prop="avatar">
        <template #default="scope">
          <img :src="scope.row.avatar" width="50px" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="手机号" prop="mobile" />
      <el-table-column align="center" label="昵称" prop="nickname" />
      <el-table-column align="center" label="所属公司" prop="orgName" />

      <el-table-column align="center" label="状态" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column :formatter="dateFormatter" align="center" label="登录时间" prop="loginDate" width="180px" />
      <el-table-column :formatter="dateFormatter" align="center" label="注册时间" prop="createTime" width="180px" />
    </el-table>
    <!-- 分页 -->
    <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNo" :total="total"
      @pagination="getList" />
  </ContentWrap>

  <!-- 划拨公司弹窗 -->
  <el-dialog v-model="orgDialogVisible" title="划拨公司" width="40%">
    <el-select v-model="orgForm.orgId" placeholder="请选择公司" size="large">
      <el-option v-for="item in orgOptions" :key="item.orgId" :label="item.orgName" :value="item.orgId" />
    </el-select>
    <template #footer>
      <el-button @click="orgDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmSetOrg">划拨</el-button>
    </template>
  </el-dialog>

</template>

<script lang="ts" setup>
import { dateFormatter } from '@/utils/formatTime'
import * as UserApi from '@/api/member/user'
import { DICT_TYPE } from '@/utils/dict'
import { ElMessageBox } from 'element-plus' // 引入消息框组件

defineOptions({ name: 'MemberUser' })

const message = useMessage() // 消息弹窗

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  nickname: null,
  mobile: null,
  loginDate: [],
  createTime: [],
  tagIds: [],
  orgId: [],
  levelId: null,
  groupId: null
})
const queryFormRef = ref() // 搜索的表单
const updateLevelFormRef = ref() // 修改会员等级表单
const updatePointFormRef = ref() // 修改会员积分表单
const UpdateBalanceFormRef = ref() // 修改用户余额表单
const selectedIds = ref<number[]>([]) // 表格的选中 ID 数组
const orgOptions = ref([]) // 公司选项列表

// 划拨相关
const orgDialogVisible = ref(false) // 划拨弹窗显示状态
const orgFilterVisible = ref(false) // 划拨弹窗显示状态
const orgForm = ref({ orgId: null, orgName: '' }) // 划拨表单数据


/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UserApi.getUserPage2(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 获取公司列表 */
const getOrgList = async () => {
  loading.value = true
  try {
    const flag = await UserApi.getOrgFilterFlag()
    if (!flag) {
      const data = await UserApi.getOrgList()
      orgFilterVisible.value = true
      orgOptions.value = data
    }
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 打开划拨公司弹窗 */
const setOrg = () => {
  if (selectedIds.value.length === 0) {
    message.warning('请先选择要操作的用户')
    return
  }
  orgDialogVisible.value = true
  orgForm.value = { orgId: null, orgName: '' }
}

/** 确认划拨公司 */
const confirmSetOrg = async () => {
  if (!orgForm.value.orgId) {
    message.warning('请选择要划拨的公司')
    return
  }

  // 获取选中的公司名称
  const selectedOrg = orgOptions.value.find(org => org.orgId === orgForm.value.orgId)
  if (!selectedOrg) {
    message.error('未找到所选公司信息')
    return
  }

  orgForm.value.orgName = selectedOrg.orgName

  // 使用 ElMessageBox 替代 useConfirm
  ElMessageBox.confirm(
    `确定要将选中的 ${selectedIds.value.length} 个用户划拨到 ${selectedOrg.orgName} 吗？`,
    '确认划拨',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        // 调用划拨接口
        await UserApi.setOrgList({
          idList: selectedIds.value.join(','),
          orgId: orgForm.value.orgId,
          orgName: orgForm.value.orgName
        })

        message.success('划拨成功')
        orgDialogVisible.value = false
        getList() // 刷新列表
      } catch (error) {
        console.error('划拨失败', error)
        message.error('划拨失败，请重试')
      }
    })
    .catch(() => {
      // 用户取消操作
    })
}

/** 打开会员详情 */
const { push } = useRouter()
const openDetail = (id: number) => {
  push({ name: 'MemberUserDetail', params: { id } })
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 表格选中事件 */
const handleSelectionChange = (rows: UserApi.UserVO[]) => {
  selectedIds.value = rows.map((row) => row.id)
}

/** 发送优惠券 */
const couponSendFormRef = ref()
const openCoupon = () => {
  if (selectedIds.value.length === 0) {
    message.warning('请选择要发送优惠券的用户')
    return
  }
  couponSendFormRef.value.open(selectedIds.value)
}

/** 操作分发 */
const handleCommand = (command: string, row: UserApi.UserVO) => {
  switch (command) {
    case 'handleUpdate':
      openForm('update', row.id)
      break
    case 'handleUpdateLevel':
      updateLevelFormRef.value.open(row.id)
      break
    case 'handleUpdatePoint':
      updatePointFormRef.value.open(row.id)
      break
    case 'handleUpdateBlance':
      UpdateBalanceFormRef.value.open(row.id)
      break
    default:
      break
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  getOrgList()
})
</script>
